<template>
  <div class="sources-container">
    <!-- 头部区域 -->
    <div class="page-header">
      <div class="page-actions">
        <el-button type="primary" icon="Plus" @click="handleAddSource"
          >新增数据源</el-button
        >
      </div>
    </div>

    <!-- 数据源卡片列表 -->
    <div class="source-cards">
      <el-row :gutter="20">
        <el-col
          v-for="source in dataSources"
          :key="source.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="8"
          :xl="6"
        >
          <el-card
            class="source-card"
            :class="{ disabled: source.status === 'disabled' }"
          >
            <!-- 状态标签 -->
            <div class="status-tag" :class="getStatusClass(source.start)">
              {{ getStatusText(source.start) }}
            </div>

            <!-- 卡片内容 -->
            <div class="card-content">
              <!-- API 地址 -->
              <div class="api-url">
                <el-link target="_blank" :underline="false">
                  <el-icon>
                    <Link />
                  </el-icon>
                  {{ source.api }}
                </el-link>
              </div>

              <!-- 信息指标 -->
              <div class="info-indicators">
                <div class="indicator">
                  <span>脚本名称: {{ source.name }}</span>
                </div>
                <!--<div class="indicator">
                  <el-icon>
                    <Timer />
                  </el-icon>
                  <span
                    >定时任务:
                    {{
                      script_freq.find((item) => item.value === source.type)
                        ?.name
                    }}</span
                  >
                </div>-->
                <div class="indicator">
                  <el-icon>
                    <Flag />
                  </el-icon>
                  <span :class="getRunStatusClass(source.status)">运行状态: {{ source.status_info }}</span>
                </div>
                <div class="indicator">
                  <el-icon>
                    <Document />
                  </el-icon>
                  <span>新增数据: </span>
                  <span
                    @click="lookVuln(source.id, source.new_count)"
                    >{{ source.new_count || 0 }}条</span
                  >
                  <span
                    class="linkSpan"
                    @click="lookVuln(source.id, source.new_count)"
                    >查看数据</span
                  >
                </div>
                <div class="indicator">
                  <el-icon>
                    <Calendar />
                  </el-icon>
                  <span>最后更新: {{ source.update_time }}</span>
                </div>
                <div v-if="source.status === 'error'" class="indicator error">
                  <el-icon>
                    <Warning />
                  </el-icon>
                  <span>{{ source.errorMessage || "API连接失败" }}</span>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="card-actions">
                <template v-if="source.start != 0">
                  <el-button
                    type="info"
                    icon="VideoPause"
                    @click="handlePauseSource(source)"
                  >
                    暂停
                  </el-button>
                </template>
                <template v-else>
                  <el-button
                    type="primary"
                    icon="VideoPlay"
                    @click="handleStartSource(source)"
                  >
                    启用
                  </el-button>
                  <el-button
                    type="danger"
                    icon="Delete"
                    @click="handleDeleteSource(source)"
                  >
                    删除
                  </el-button>
                </template>
                <el-button
                  type="primary"
                  plain
                  icon="Edit"
                  :disabled="source.start !== 0"
                  @click="handleEditSource(source)"
                >
                  编辑
                </el-button>
                <el-button
                  plain
                  icon="RefreshRight"
                  :disabled="source.new_count == '0'"
                  @click="handleSyncSource(source.id)"
                >
                  同步
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div
        class="pagination-container"
        style="display: flex; justify-content: center; margin-top: 20px"
      >
        <el-pagination
          v-model:current-page="currentPage4"
          v-model:page-size="pageSize4"
          :page-sizes="[10, 20, 50, 100]"
          :size="size"
          :disabled="disabled"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑数据源弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加数据源' : '编辑数据源'"
      width="600px"
    >
      <el-form
        ref="sourceFormRef"
        :model="sourceForm"
        :rules="sourceRules"
        label-width="auto"
        label-position="right"
        class="form-wrapper"
      >
        <el-form-item label="脚本任务" prop="source">
          <el-select
            v-model="sourceForm.source"
            placeholder="请选择数据源类型"
            style="width: 100%"
            @change="handleSelectSource"
            :disabled="dialogType === 'edit'"
          >
            <el-option
              v-for="item in sourceList"
              :key="item.source"
              :label="item.name"
              :value="item.source"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="脚本名称">
          <el-input
            v-model="selectSource.name"
            placeholder="脚本名称"
            disabled
          />
        </el-form-item>
        <el-form-item label="脚本地址">
          <el-input
            v-model="selectSource.apiUrl"
            placeholder="脚本地址"
            disabled
          />
        </el-form-item>
        <!--<el-form-item label="定时任务" prop="type">
          <el-radio-group v-model="sourceForm.type">
            <el-radio
              v-for="item in script_freq"
              :key="item.value"
              :label="item.value"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitSourceForm"
            :loading="submitLoading"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <NewVulnDialog v-model:visible="vuln_dialogVisible" :vulnId="openVulnId" />
  </div>
</template>

<script setup>
import NewVulnDialog from "./components/NewVulnDialog.vue";
import { ref, onMounted, onUnmounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Link,
  Timer,
  Document,
  Calendar,
  Warning,
} from "@element-plus/icons-vue";
import {
  getScriptList,
  createTask,
  updateTask,
  stopTask,
  startTask,
  dataSync,
  getSourceInfo,
  deleteTask,
} from "@/api/intelligence";

// 根据状态获取样式类名
const getRunStatusClass = (status) => {
  if (status > 100) {
    return 'status-failed';
  } else {
    return 'status-running';
  }
};

const script_freq = ref([
  {
    name: "每天一次",
    value: 1,
  },
  {
    name: "每周一次",
    value: 2,
  },
]);
const selectSource = reactive({
  name: "",
  apiUrl: "",
});
const dataSources = ref([]);
const timerId = ref(null);
const vuln_dialogVisible = ref(false);
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
// const sourceForm = ref({
//   type: 2,
// });
const sourceForm = ref({});
const sourceFormRef = ref(null);
const submitLoading = ref(false);
const currentSourceId = ref(null);
const sourceList = ref([]);
const queryParams = reactive({
  page_index: 1,
  page_size: 10,
});
const openVulnId = ref(0);

const total = ref(0);
// 表单验证规则
const sourceRules = {
  source: [{ required: true, message: "请选择脚本任务", trigger: "change" }],
  type: [{ required: true, message: "请选择更新频率", trigger: "change" }],
};

const lookVuln = (id, count) => {
  if (count < 1) {
    ElMessage.warning("此源没有新增数据");
    return;
  }
  vuln_dialogVisible.value = true;
  openVulnId.value = id;
};

const fetchSourceInfo = async () => {
  const response = await getSourceInfo();
  let arr = [];
  for (const key in response.data) {
    arr.push(response.data[key]);
  }
  sourceList.value = arr;
};
fetchSourceInfo();

// 脚本任务
const handleSelectSource = (value) => {
  let sourceInfo = sourceList.value.find((item) => item.source === value);
  selectSource.name = sourceInfo.name;
  selectSource.apiUrl = sourceInfo.api;
};

// 获取数据源状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 1:
      return "status-running";
    case 0:
      return "status-disabled";
    default:
      return "";
  }
};

// 获取数据源状态文本
const getStatusText = (status) => {
  switch (status) {
    case 1:
      return "已启用";
    case 0:
      return "未启用";
    default:
      return "未知";
  }
};

// 获取数据源列表
const fetchDataSources = async () => {
  // 调用API获取数据
  const response = await getScriptList(queryParams);
  dataSources.value = response.data;
  total.value = response.total_items;
};

// 添加数据源
const handleAddSource = () => {
  dialogType.value = "add";
  resetSourceForm();
  dialogVisible.value = true;
};

// 编辑数据源
const handleEditSource = (source) => {
  dialogType.value = "edit";
  currentSourceId.value = source.id;
  sourceForm.value = source;
  dialogVisible.value = true;
};

// 暂停数据源
const handlePauseSource = async (source) => {
  try {
    ElMessageBox.confirm(`确定要停止 ${source.name} 的数据同步吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      // 调用API停止任务
      const response = await stopTask({ id: source.id });

      // 更新本地状态
      const index = dataSources.value.findIndex(
        (item) => item.id === source.id
      );
      if (index !== -1) {
        dataSources.value[index].status = "disabled";
      }

      ElMessage.success("数据源已停用");
      fetchDataSources();
    });
  } catch (error) {
    console.error("停用数据源失败:", error);
    ElMessage.error("停用数据源失败");
  }
};

// 启动数据源
const handleStartSource = async (source) => {
  try {
    // 调用API启动任务
    const response = await startTask({ id: source.id });
    // 更新本地状态
    const index = dataSources.value.findIndex((item) => item.id === source.id);
    if (index !== -1) {
      dataSources.value[index].status = "running";
    }
    ElMessage.success("数据源已启用");
    fetchDataSources();
  } catch (error) {
    console.error("启用数据源失败:", error);
    ElMessage.error("启用数据源失败");
  }
};

// 同步数据源
const handleSyncSource = async (id) => {
  // 调用API同步数据
  const response = await dataSync({
    id,
  });
  ElMessage.success("数据源同步完成");
  fetchDataSources();
};

// 删除数据源
const handleDeleteSource = async (source) => {
  ElMessageBox.confirm(`确定要删除 ${source.name} 的数据源吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const response = await deleteTask({ id: source.id });
    ElMessage.success(response.msg);
    fetchDataSources();
  });
};

// 提交表单
const submitSourceForm = async () => {
  if (!sourceFormRef.value) return;

  try {
    await sourceFormRef.value.validate(async (valid) => {
      if (!valid) return;
      submitLoading.value = true;
      if (dialogType.value === "add") {
        // 调用API创建任务
        await createTask(sourceForm.value);
        ElMessage.success("添加成功");
      } else {
        // 调用API更新任务
        await updateTask({
          id: sourceForm.value.id,
          type: sourceForm.value.type,
        });
        ElMessage.success("更新成功");
      }
      dialogVisible.value = false;
      resetSourceForm();
      fetchDataSources();
      submitLoading.value = false;
    });
  } catch (error) {
    dialogVisible.value = false;
    submitLoading.value = false;
  }
};
const handleSizeChange = (size) => {
  queryParams.page_size = size;
  fetchDataSources();
};
const handleCurrentChange = (page) => {
  queryParams.page_index = page;
  fetchDataSources();
};
// 重置表单
const resetSourceForm = () => {
  sourceForm.value = {
    type: 2,
  };

  if (sourceFormRef.value) {
    sourceFormRef.value.resetFields();
  }

  currentSourceId.value = null;
};

// 初始化
onMounted(() => {
  fetchDataSources();
  timerId.value = setInterval(fetchDataSources, 10000);
});

onUnmounted(() => {
  if (timerId.value) {
    clearInterval(timerId.value);
    timerId.value = null;
  }
});
</script>

<style lang="scss" scoped>
:deep(.el-button) {
  margin: 0 !important;
  margin-right: 10px !important;
  margin-bottom: 10px !important;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background: none;
}

/* 脚本名称和脚本地址输入框样式 */
.el-input.is-disabled  {
  background-color: #f5f5f5 !important; /* 白色主题下的灰色背景 - 提高优先级 */
}

/* 暗色主题适配 */
.dark .el-input.is-disabled  {
  background-color: #343434 !important; /* 暗色主题下的匹配背景色 - 提高优先级 */
}

.status-failed {
  color: #f56c6c;

  .status-indicator {
    background-color: #f56c6c;
    box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
  }
}

.status-running {
  color: #1890ff;

  .status-indicator {
    background-color: #1890ff;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  }
}

.sources-container {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .page-title {
      font-size: 20px;
      font-weight: bold;
      color: var(--el-text-color-primary);
    }

    .page-actions {
      display: flex;
      gap: 16px;

      .search-input {
        width: 240px;
      }
    }
  }
  .form-wrapper {
    padding-top: 20px;
  }

  .source-cards {
    margin-bottom: 20px;

    .source-card {
      margin-bottom: 20px;
      position: relative;
      transition: all 0.3s;
      border: 1px solid var(--el-border-color-light);

      &.disabled {
        opacity: 0.7;
      }

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .status-tag {
        position: absolute;
        top: 0;
        right: 0;
        padding: 4px 10px;
        font-size: 12px;
        color: white;
        border-bottom-left-radius: 4px;

        &.status-running {
          background-color: var(--el-color-success);
        }

        &.status-disabled {
          background-color: var(--el-color-info);
        }

        &.status-error {
          background-color: var(--el-color-danger);
        }
      }

      .card-content {
        // padding: 10px 0;

        .api-url {
          margin-bottom: 15px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          display: flex;
          align-items: center;

          a {
            color: var(--el-color-primary);
            display: flex;
            align-items: center;
            gap: 5px;
          }
        }

        .info-indicators {
          margin-bottom: 20px;

          .indicator {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 10px;
            color: var(--el-text-color-secondary);
            font-size: 14px;

            &.error {
              color: var(--el-color-danger);
            }
          }
        }

        .card-actions {
          display: flex;
          flex-wrap: wrap;
        }
      }
    }
  }

  .linkSpan {
    color: var(--primary-color);
    cursor: pointer;
  }
}
</style>
